package de.slothsoft.wasbinich.android.database.webservice;

import android.accounts.AccountManager;
import android.os.Bundle;
import android.util.Log;
import de.slothsoft.android.authenticator.AuthenticationUtil;
import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.LoginBean;
import de.slothsoft.wasbinich.core.database.webservice.AbstractOAuth2Authenticator.Token;
import de.slothsoft.wasbinich.core.database.webservice.RestCommunicator;

public class OAuth2LoginBean implements LoginBean {

    private final AndroidOAuth2Authenticator authenticator;

    public OAuth2LoginBean(RestCommunicator restCommunicator) {
	this.authenticator = new AndroidOAuth2Authenticator(restCommunicator);

	Bundle options = new Bundle();
	options.putString(AuthenticationUtil.OPTION_APPLICATION, "wasbinich"); //$NON-NLS-1$
	AuthenticationUtil.options = options;
    }

    @Override
    public void logOut() {
	// nothing to do
    }

    @Override
    public boolean isLoggedIn() {
	AccountManager accountManager = this.authenticator.getAccountManager();
	return accountManager.getAccountsByType(AuthenticationUtil.ACCOUNT_ID).length > 0;
    }

    @Override
    public synchronized String getLoginToken() throws DatabaseException {
	Token token = this.authenticator.getToken();
	if (token != null) {
	    Log.d("slothsoft", "Using token: " + token.accessToken + ", expiring " + token.expireDate); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
	} else {
	    Log.e("slothsoft", "No token found for OAuth2LoginBean!"); //$NON-NLS-1$ //$NON-NLS-2$
	}
	return token == null ? null : token.accessToken;
    }
}
